﻿//======================================================================
//
//        Copyright (C) 2015   
//        All rights reserved
//
//        filename : MakingBadCard
//        description : 制卡坏卡
//        created by XXX at  20160115
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using System.Data;
using System.Text;

namespace CardLogistics.Web.MainPage.CardRecovery.NotSaleCard
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.CardRecovery.NotSaleCardData DAL = new DAL.CardRecovery.NotSaleCardData();
        private static readonly CardLogistics.DAL.CardRecovery.NotSaleCard_DetailData DDAL = new CardLogistics.DAL.CardRecovery.NotSaleCard_DetailData();
        string recoveryId = "";//未售问题卡Id
        public string TitleName
        {
            get;
            set;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGroup();
                if (Mid == "100900")
                {
                    tr_SALE.Visible = false;
                    RECOVERYNO.Value = GetBillNumber("制卡坏卡");//制卡坏卡
                }
                else
                    RECOVERYNO.Value = GetBillNumber("未售问题卡回收");//未售问题卡
                InitControl();

            }
        }

        #region 编辑时绑定值
        /// <summary>
        /// 编辑时绑定值
        /// </summary>
        public void InitControl()
        {
            TitleName = GetStatusInfo(0, "未售问题卡回收");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    CardLogistics.Model.CardRecovery.NotSaleCard pData = DAL.GetModel(_key);
                    SetWebControls(this.Page, pData);
                    DataTable dt = DDAL.GetInfoByRecoveryId(pData.ID);
                    string detName = "";
                    string detId = "";
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detName += dr["StartCardNo"].ToString() + "[" + dr["EndCardNo"].ToString() + "]" + "[" + dr["CardAmount"].ToString() + "];";
                            detId += dr["StartCardNo"].ToString() + "|" + dr["EndCardNo"].ToString() + "|" + dr["CardAmount"].ToString() + ";";
                        }
                        hf_detailId.Value = detId.TrimEnd(';');
                    }
                    RETURNPOINT.SelectedValue = pData.RETURNPOINT;
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (pData.IsSubmit == 0 || pData.IsSubmit == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    WriteJavaScript("document.getElementById(\"REMARKS\").value = \"adafdasfd\";", false);
                    TitleName = GetStatusInfo(int.Parse(pData.IsSubmit.ToString()), "未售问题卡回收");
                }
            }

        }
        #endregion

        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                if (result.Split(',')[0] == "ok")
                {
                    recoveryId = result.Split(',')[1];//获取卡片出库ID
                    EncapNotSaleCardDetailModel();//插入未售卡问题明细

                    InsertLog("保存未售问题卡回收信息,回收单号:" + RECOVERYNO.Value);
                    ReturnListInfo();
                }
                else if (result.Split(',')[1] == "-1")
                {
                    ShowMessageBox("回收单号已存在,不允许重复！");
                    return;
                }
                else
                {
                    ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                if (result.Split(',')[0] == "ok")
                {
                    InsertAppInfo(11, result.Split(',')[1]); // 11未售问题卡回收
                    recoveryId = result.Split(',')[1];//获取卡片出库ID
                    EncapNotSaleCardDetailModel();//插入未售卡问题明细
                    InsertLog("保存并提交未售问题卡回收信息,回收单号:" + RECOVERYNO.Value);
                    ReturnListInfo();
                }
                else if (result.Split(',')[1] == "-1")
                {
                    ShowMessageBox("回收单号已存在,不允许重复！");
                    return;
                }
                else
                {
                    ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 未售问题卡回收信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            CardLogistics.Model.CardRecovery.NotSaleCard model = new Model.CardRecovery.NotSaleCard();
            model = GetWebControls<CardLogistics.Model.CardRecovery.NotSaleCard>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;
            model.LASTUPDATEDATE = DateTime.Now;
            model.RETURNPOINT = RETURNPOINT.SelectedValue.ToString();
            model.IsSubmit = issubmit;
            if (Mid == "100900")//INFOTYPE 0=制卡坏卡 1=未售问题卡
            {
                model.RETURNPOINT = "";
                model.INFOTYPE = 0;
            }
            else
                model.INFOTYPE = 1;

            string result = string.Empty;
            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model);
            }
            else
            {
                result = DAL.Add(model);
                if (Mid == "100900")
                    ChgBillNumber("制卡坏卡");
                else
                    ChgBillNumber("未售问题卡回收");
            }
            return result;
        }

        #region 插入半成品/成品卡出库明细信息
        /// <summary>
        /// 插入半成品/成品卡出库明细信息
        /// </summary>
        /// <returns></returns>
        private void EncapNotSaleCardDetailModel()
        {
            string FileValue = hf_detailId.Value; //半成品/成品卡出库明细字段
            string[] split = FileValue.Split(';');//以分号分隔
            int count = split.Length; //计算行数
            int result = 0; //受影响的行数
            StringBuilder strSql = new StringBuilder();

            strSql.Append(" delete from NotsaleCard_Detail where RecoveryId ='" + recoveryId + "'");
            result = CardLogistics.DAL.DbHelperSQL.ExecuteSql(strSql.ToString());
            for (int i = 0; i < count; i++)
            {
                strSql = new StringBuilder();//初始化
                strSql.Append("insert into NotsaleCard_Detail");
                strSql.Append("(RecoveryId,CardAmount,StartCardNo,EndCardNo)");
                strSql.Append(" values(");
                strSql.Append("'" + recoveryId + "',");
                strSql.Append("" + split[i] + "");
                strSql.Append(")");
                result = CardLogistics.DAL.DbHelperSQL.ExecuteSql(strSql.ToString());
            }
            if (result > 0)
            {
                ReturnListInfo();
            }
        }
        #endregion

        #region 绑定机构/网点树列表
        /// <summary>
        /// 绑定根节点
        /// </summary>
        void BindGroup()
        {
            DataTable dt = new DAL.Basic.Basic_SalesInfoData().GetList(" ISDELETE=0 ", "*");//获取所有节点
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    if (row["PARENTID"].ToString().Trim() == "0")//绑定根节点
                    {
                        this.RETURNPOINT.Items.Insert(RETURNPOINT.Items.Count, new ListItem(row["SALESNAME"].ToString(), row["Id"].ToString()));
                        this.BindDropChildItem(this.RETURNPOINT, dt, row["Id"].ToString(), 1);
                    }
                }
            }
        }
        /// <summary>
        /// 绑定子节点
        /// </summary>
        /// <param name="d"></param>
        /// <param name="dt"></param>
        /// <param name="id"></param>
        /// <param name="length"></param>
        void BindDropChildItem(DropDownList d, DataTable dt, string id, int length)
        {
            DataRow[] rows = dt.Select("PARENTID='" + id + "'", "Id DESC");//取出id子节点进行绑定
            for (int i = 0; i < rows.Length; i++)
            {
                this.RETURNPOINT.Items.Insert(RETURNPOINT.Items.Count, new ListItem(this.SpaceLength(length) + rows[i]["SALESNAME"].ToString(), rows[i]["Id"].ToString()));
                this.BindDropChildItem(d, dt, rows[i]["Id"].ToString(), length + 1);//空白数目加1
            }
        }
        /// <summary>
        /// 子节点前面的空白数
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        string SpaceLength(int i)
        {
            string space = "┊";
            for (int j = 0; j < i; j++)
            {
                space += "┈┈";//注意这里的空白是智能abc输入法状态下的v11字符；┊┈┈
            }
            return space;
        }
        #endregion
    }
}